<?php

namespace app\common\library;

use app\admin\model\WechatUser;
use EasyWeChat\Factory;
use fast\Tree;
use Overtrue\Socialite\AuthorizeFailedException;
use think\AddonService;
use think\Exception;
use app\admin\model\AuthRule;
use think\facade\Db;

class Wechat
{

    protected static $wechat_config = null;

    protected static $wechatapp = null;



    public static function init_wechatapp($config){

        if(self::$wechat_config == null){
            self::$wechat_config = $config;
        }
        if(self::$wechatapp == null){
                self::$wechatapp = Factory::officialAccount($config);
        }
    }
    public function getWechatApp(){
        return self::$wechatapp;
    }

    public function getWechatOauth(){
        return self::$wechatapp->oauth;
    }

    public function getAuthUrl($callbackurl,$user_type = "snsapi_base"){
        $auth =  $this->getWechatOauth();;
        $response = $auth->scopes([$user_type])->redirect($callbackurl);
        preg_match_all("/<a href=\"(.*)?\"/",$response->getContent(),$array2);
        $url = str_replace("amp;","",$array2[1][0]);
        return ["status"=>1,"msg"=>"获取成功","data"=>$url];
    }

    public function getUserInfo(){
        $auth =  $this->getWechatOauth();
        try {
            $user =  $auth->user();
        }catch (AuthorizeFailedException $e){
            return ["status"=>0,"msg"=>"获取失败","data"=>$e->getMessage()];
        }
        $wechat_user = WechatUser::where("openid",$user->id)->find();
        if(!$wechat_user){
            $wechat_user = WechatUser::create(["openid"=>$user->id,"nickname"=>$user->name,"headimgurl"=>$user->avatar]);
        }
        return ["status"=>1,"msg"=>"获取成功","data"=>$wechat_user];
    }




     public function test(){
         echo "test222";
     }

    /*
       * 菜单创建
       */
    public  function menuAdd(){

        $buttons = [
            [
                "type" => "view",
                "name" => "下载APP",
                "url"  => config('system.api.url')."/download.html"
            ],
            [
                "type" => "view",
                "name" => "个人中心",
                "url"  => config('system.api.url')."/h5"
            ]
        ];
        return $this->app->menu->create($buttons);
    }




}
